package de.swta.freezay.admin.category;

import de.swta.*;
import de.swta.freezay.components.ActionPanel;
import de.swta.freezay.components.OptionContentPanel;
import de.swta.freezay.database.JPAController;
import de.swta.freezay.database.controller.exceptions.NonexistentEntityException;
import de.swta.freezay.database.dbEntities.Category;
import de.swta.freezay.database.wicketAdapter.CategoryDataProvider;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.ISortStateLocator;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.AbstractReadOnlyModel;

/**
 *
 * @author Jan Korreck
 */
public class CategoryView extends Panel {

    /** Modal window for editing one category. */
    private final ModalWindow modalWindow = new ModalWindow("modal");
    /** markup container for updating the listview. */
    private WebMarkupContainer theContainer;
    /** Dataview for the html- table. */
    private DataView<Category> categoryView;

    /**
     * Creates a new instance of CategoryView.
     */
    public CategoryView() {
        this("CategoryView");
    }

    /**
     * Creates a new instance of CategoryView.
     * @param id ID of the panel.
     */
    public CategoryView(String id) {
        super(id);
        init();
    }

    /**
     * Initializes the components of the panel.
     */
    private void init() {

        add(modalWindow);

        CategoryDataProvider dataProvider = new CategoryDataProvider();

        /* The dataview for all categories. */
        categoryView = new DataView<Category>("category",
                dataProvider, 15) {

            @Override
            protected void populateItem(final org.apache.wicket.markup.repeater.Item<Category> item) {

                final Category c = item.getModelObject();

                item.add(new Label("Name", c.getName()));

                /* Button for editiing a category. */
                item.add(new ActionPanel("Action", "Editieren", new AjaxLink("select") {

                    @Override
                    public void onClick(AjaxRequestTarget target) {

                        /* When button is clicked - modal window is shown. */
                        modalWindow.setContent(
                                new CategoryEditPanel(modalWindow.getContentId(), c.getId(), true) {

                            @Override
                            public void confirmLinkClicked(AjaxRequestTarget target) {
                                modalWindow.close(target);
                                /* update the table. */
                                target.addComponent(CategoryView.this.theContainer);
                            }
                        });

                        modalWindow.setTitle("Kategorie editieren");
                        modalWindow.setInitialHeight(150);
                        modalWindow.setInitialWidth(250);
                        modalWindow.show(target);
                    }
                }));

                /* Button for category - delete. */
                item.add(new ActionPanel("Action2", "Löschen", new AjaxLink("select") {

                    @Override
                    public void onClick(AjaxRequestTarget target) {


                        modalWindow.setContent(new OptionContentPanel(modalWindow.getContentId()) {

                            public void onSelect(AjaxRequestTarget target, String selection) {

                                /* Confirm button was clicked. */
                                if (!JPAController.CategoryJpaController.isUsed(c.getId())) {
                                    /* If it is used nowhere - delete it. */
                                    try {
                                        JPAController.CategoryJpaController.destroy(c.getId());
                                    } catch (NonexistentEntityException ex) {
                                        Logger.getLogger(CategoryView.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    modalWindow.close(target);
                                    target.addComponent(CategoryView.this.theContainer);
                                } else {
                                    /* Show error message in the modal window. */
                                    error("Löschen nicht möglich! \n " +
                                            "Die Kategorie wird bereits verwendet");
                                }
                            }

                            public void onCancel(AjaxRequestTarget target) {
                                /* Cancel was clicked - just close the modal window. */
                                modalWindow.close(target);
                            }
                        });

                        /* Confirm message. */
                        ((OptionContentPanel) modalWindow.get(
                                modalWindow.getContentId())).setMessageText(
                                "Wollen sie die Kategorie '" + c.getName()
                                + "' wirklich löschen?");
                        
                        modalWindow.setTitle("Kategorie löschen");
                        modalWindow.setInitialHeight(200);
                        modalWindow.setInitialWidth(300);
                        modalWindow.show(target);
                    }
                }));

                /** css- style for even/ odd rows. */
                item.add(new AttributeModifier("class", true,
                        new AbstractReadOnlyModel<String>() {

                            @Override
                            public String getObject() {
                                return (item.getIndex() % 2 == 1) ? "even" : "odd";
                            }
                        }));

            }
        };

        /* The markupcontainer with allo it's components. */
        theContainer = new WebMarkupContainer("theContainer");
        theContainer.setOutputMarkupId(true);
        theContainer.add(categoryView.setOutputMarkupId(true));
        theContainer.add(createOrderByBorder("orderByCategoryName", "name",
                dataProvider, categoryView).setOutputMarkupId(true));
        add(theContainer);
        /* Navigation. */
        add(new PagingNavigator("pagenavigation_top", categoryView).setOutputMarkupId(true));
        add(new PagingNavigator("pagenavigation_bottom", categoryView).setOutputMarkupId(true));
        

        /** Button to add a new category. */
        add(new AjaxLink("addCategory") {

            @Override
            public void onClick(AjaxRequestTarget target) {

                modalWindow.setContent(new CategoryEditPanel(modalWindow.getContentId(), -1, false) {

                    @Override
                    public void confirmLinkClicked(AjaxRequestTarget target) {
                        /* Confirm was clicked - the new category will be added by the editPanel. */
                        modalWindow.close(target);
                        target.addComponent(CategoryView.this.theContainer);
                    }
                });

                modalWindow.setTitle("Kategorie erstellen");
                modalWindow.show(target);
            }
        });
    }

    /**
     * Creates and returns an OrderByBorder.
     * @param id Id of the Border.
     * @param table Table wich content is sorted
     * @param sortStateLocator Locator for the sorting Border.
     * @param view Dataview that displays the categories.
     * @return Returns an OrderByBorder.
     */
    private final OrderByBorder createOrderByBorder(final String id,
            final String table, final ISortStateLocator sortStateLocator,
            final DataView<?> view) {

        return new OrderByBorder(id, table, sortStateLocator) {

            @Override
            protected void onSortChanged() {
                view.setCurrentPage(0);
            }
        };
    }
}
